import { loadScript, browser as browserInfo, isiOS, isAndroid } from '../utils'
import { request } from '@/plugins/http.plugin'

// 微信每个页面只能设置一此分享
const isUseNewApi = Date.now() > 1568505600000
function configWX (isPosterPage: boolean = false, wxOptions?: ShareData) {
  if (!browserInfo.isWechat) {
    return false
  }
  if (((isiOS && window.visitPageCount === 1) || (isAndroid && isPosterPage))) {
    Promise.all([
      request({
        url: 'Training/GetWxSdkConfig',
        data: {
          url: location.href.split('#')[0],
          Token: '-1',
        },
      }),
      loadScript(`//res2.wx.qq.com/open/js/jweixin-${isUseNewApi ? '1.4.0' : '1.3.2'}.js`, 'jweixin140'),
    ]).then(([wxconfig]) => {
      wx.config({
        // debug: !!process.env.VUE_APP_FOR_TEST || process.env.NODE_ENV !== 'production',
        debug: false,
        ...wxconfig as any,
        jsApiList: [
          'updateAppMessageShareData',
          'updateTimelineShareData',
          'onMenuShareAppMessage',
          'onMenuShareTimeline',
          'onMenuShareQQ',
          'onMenuShareWeibo',
          'onMenuShareQZone',
        ],
      })
      if (wxOptions) {
        // 分享设置页作为第一个页面ios也在此设置
        setWXShareData(wxOptions)
      }
      wx.error(err => {
        console.log('wx.config error', err)
      })
    })
  }
  if (isiOS && window.visitPageCount !== 1 && wxOptions) {
    // ios分享设置页不是第一个页面此设置
    console.log('ios分享设置页不是第一个页面此设置', wxOptions)
    setWXShareData(wxOptions)
  }
  return true
}

function setWXShareData (wxOptions: ShareData) {
  wx.ready(() => {
    // console.log('wx ready')
    if (isUseNewApi) {
      // TMD不知道为社么不行，明明显示ok的
      wx.updateAppMessageShareData(wxOptions)
      wx.updateTimelineShareData(wxOptions)
    } else {
      wx.onMenuShareAppMessage(wxOptions)
      wx.onMenuShareTimeline(wxOptions)
      wx.onMenuShareQQ(wxOptions)
      wx.onMenuShareWeibo(wxOptions)
      wx.onMenuShareQZone(wxOptions)
    }
  })
}

function setShareData (options: ShareData) {
  if (browserInfo.isQQ || browserInfo.isQZone) {
    loadScript('//qzonestyle.gtimg.cn/qzone/qzact/common/share/share.js', 'shareJS')
      .then(() => {
        // QQ 不支持自定义分享内容
        setShareInfo({
          title: options.title,
          summary: options.desc,
          pic: options.imgUrl,
          url: options.link,
        })
      })
  } else if (!configWX(true, options)) {
    loadScript('//jsapi.qq.com/get?api=app.share', 'mbqqshare').then(res => {
      console.log('isQQ browser', browserInfo.isQQMBrowser)
      if (window.browser && browser.app) {
        browserInfo.isQQMBrowser = true
      }
    })
  }
}

function showShare (shareData: ShareData) {
  if (browserInfo.isWechat) {
    return 'wx'
  }
  if (browserInfo.isQQ) {
    return 'qq'
  }
  if (browserInfo.isQQMBrowser) {
    loadScript('//jsapi.qq.com/get?api=app.share', 'mbqqshare').then(() => {
      (window as any).browser.app.share({
        title: shareData.title,
        description: shareData.desc,
        url: shareData.link,
        img_url: shareData.imgUrl,
        from: shareData.from || '',
        to_app: void 0,
      })
    })
    return 'qqmb'
  }
  if (browserInfo.isUCMBrowser) {
    if (ucweb && ucweb.startRequest) {
      ucweb.startRequest('shell.page_share', [
        shareData.title,
        shareData.desc,
        shareData.link,
        '',
        '',
        shareData.from,
        shareData.imgUrl,
      ])
    } else if (ucbrowser) {
      if (ucbrowser.web_shareEX) {
        ucbrowser.web_shareEX(
          JSON.stringify({
            title: shareData.title,
            content: shareData.desc,
            sourceUrl: shareData.link,
            imageUrl: shareData.imgUrl,
            source: shareData.from,
            target: void 0,
          })
        )
      } else {
        ucbrowser.web_share(
          shareData.title,
          shareData.desc,
          shareData.link,
          void 0,
          '',
          shareData.from,
          ''
        )
      }
    }
    return 'uc'
  }
  return 'others'
}

export { setShareData, showShare, configWX }

interface ShareData {
  title: string // 分享标题
  desc: string // 分享描述
  link: string // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  imgUrl: string // 分享图标
  from?: string //
  success?: any // 设置成功
}

declare const setShareInfo: any
declare const ucweb: any
declare const ucbrowser: any
declare const browser: any
